package service

import (
	"fmt"
	"strings"
	"time"

	"commonUtils/utils"
)

type MD map[string]interface{}

type BaseHttpService struct {
	*utils.Cache
	HttpClient     *utils.HTTPClient
	AuthKey        string
	Host           string
	ControllerName string
	BaseUrl        string
}

func NewBaseHttpService(key string, host string, ctrlname string) *BaseHttpService {
	if utils.EndWith(host, "/") {
		host = host[0 : len(host)-1]
	}

	if utils.BeginWith(ctrlname, "/") {
		ctrlname = ctrlname[1:]
	}

	ret := &BaseHttpService{
		Cache:          utils.NewCache(utils.NoExpiration, utils.DefaultExpiration),
		HttpClient:     utils.NewHTTPClient(),
		AuthKey:        key,
		Host:           host,
		ControllerName: ctrlname,
		BaseUrl:        strings.ToLower(host + "/" + ctrlname),
	}

	return ret
}

func (b *BaseHttpService) Api(action string, data MD, out interface{}) error {

	if utils.BeginWith(action, "/") {
		action = strings.ToLower(action[1:])
	}

	url := b.BaseUrl + "/" + action
	if nil != data {
		data["time"] = time.Now().Unix()
	} else {
		data = map[string]interface{}{
			"time": time.Now().Unix(),
		}
	}
	ret, code, _, err := b.HttpClient.Api(url, data, b.AuthKey)
	if err != nil {
		return err
	}
	if code != 200 {
		return fmt.Errorf("%s", ret)
	}
	if ret != "" && out != nil {
		utils.Info("ret : %s", ret)
		if err = utils.JsonToStruct(ret, out); err != nil {
			return err
		}
	}
	return nil
}

func (a *BaseHttpService) Post(action string, data interface{}, out interface{}) error {

	m, err := utils.ToMap(data)
	if err != nil {
		return err
	}

	return a.Api(action, m, out)
}
